﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using TsCore;



namespace TsWeb.Followers
{
    public partial class ManageUsers : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                BindUserAccounts();
        }

        private void BindUserAccounts()
        {
            UserAccounts.DataSource = Membership.GetAllUsers();
            UserAccounts.DataBind();
            if (UserAccounts.HeaderRow != null)
            {
                UserAccounts.HeaderRow.TableSection = TableRowSection.TableHeader;
            }           
        }
        
        private void BindUserDetails(String UserName)
        {
            List<String> userRoles = new List<string>();
            if (UserName != null)
                userRoles = TsSystem.Instance.GetUserRoles(UserName).ToList<String>();
           
            UsersRoleList.DataSource = TsSystem.Instance.GetRoles();
            UsersRoleList.DataBind();
            foreach (RepeaterItem item in UsersRoleList.Items)
            {
                CheckBox chk = (CheckBox)item.FindControl("RoleCheckBox");
                if (userRoles.Contains(chk.Text))
                    chk.Checked = true;
                else
                    chk.Checked = false;
            }
        }

        protected void UpdateUserButton_Click(object sender, EventArgs e)
        {
            string opt = Session["Action"].ToString();
            switch (opt)
            {
                case "Update":
                    {

                        TsUser updatedUser = (TsUser)Session["UpdatedUser"];

                        updatedUser.Name = NameTxt.Text;
                        updatedUser.Surname = SurnameTxt.Text;
                        updatedUser.Email = EmailTxt.Text;
                        List<string> RolList = new List<string>();



                        foreach (RepeaterItem item in UsersRoleList.Items)
                        {
                            CheckBox chk = (CheckBox)item.FindControl("RoleCheckBox");
                            if (chk.Checked)
                            {
                                RolList.Add(chk.Text);
                            }


                        }
                        TsSystem.Instance.UpdateUser(updatedUser, RolList);
                    };break;
                case "Create":
                    {
                        List<String> TsRoles = new List<string>();
                        foreach (RepeaterItem ri in UsersRoleList.Items)
                        {
                            CheckBox RoleCheckBox = ri.FindControl("RoleCheckBox") as CheckBox;
                            if (RoleCheckBox.Checked)
                                TsRoles.Add(RoleCheckBox.Text);
                        }
                        TsSystem.Instance.CreateNewUser(NameTxt.Text, SurnameTxt.Text, UserNameTxt.Text, PasswordTxt.Text, EmailTxt.Text, TsRoles.ToArray());
                    };break;
                
            }
            BindUserAccounts();
        }

        protected void UserAccounts_SelectedIndexChanged1(object sender, EventArgs e)
        {
            //string a = UserAccounts.SelectedValue.ToString();
          
        }

        protected void ButtonCreateUser_Click(object sender, EventArgs e)
        {
            UserButton.Text = "Crear usuario";
            Session["Action"] = "Create";
            showPasswordFields(true);
            CleanUserForm();
            UserNameTxt.ReadOnly = false;
            BindUserDetails(null);
            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "$('#myModal').modal('show');", true);
            //ModalPopupExtender1.Show();
        }

        private void CleanUserForm()
        {
            UserNameTxt.Text = "";
            NameTxt.Text = "";
            SurnameTxt.Text = "";
            EmailTxt.Text = "";
        }
  


        private void showPasswordFields(bool visible)
        {
            PasswordLabel.Visible = visible;
            ConfirmPasswordLabel.Visible = visible;
            PasswordTxt.Visible = visible;
            ConfirmPasswordTxt.Visible = visible;
        }

        protected void UserAccounts_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = UserAccounts.Rows[index];
            string UserName = row.Cells[0].Text;
            if (e.CommandName == "EditCommand")
            {
          
                TsUser tu = TsSystem.Instance.GetUser(UserName);
                Session["UpdatedUser"] = tu;
                UserNameTxt.Text = UserName;
                NameTxt.Text = tu.Name;
                SurnameTxt.Text = tu.Surname;
                EmailTxt.Text = tu.Email;
                showPasswordFields(false);
                BindUserDetails(UserName);
                UserNameTxt.ReadOnly = true;

                UserButton.Text = "Actualizar usuario";
                Session["Action"] = "Update";
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "$('#myModal').modal('show');", true);
                //ModalPopupExtender1.Show();
            }
            if (e.CommandName == "DeleteCommand")
            {
                TsSystem.Instance.RemoveUser(UserName);
                //ModalMessageLabel.Text = UserName + " ha sido eliminado correctamente.";
                //MessageModal.Show();


            }

        }

    }
}